package com.runfast.waimai.web.controller.Driver_controller;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Description:
 * @Auther: chenzheng
 * @Date: 2018/12/3 10:17
 **/
@Controller
@RequestMapping("/driver/*")
public class DriverFileLoadController {

    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "Bku4MNJHn2m-qHPxZ4jDTkkV-tIw6U-u6Ex2mUrW";
    String SECRET_KEY = "eMSL04-fhF-IggfUsa_v87IcX_ehREMA0gVj3iCL";
    //要上传的空间
    String bucketname = "runfast";
    //上传到七牛后保存的文件名
    //String key ="/uplaod/"+String.valueOf(System.currentTimeMillis());
    //上传文件的路径
    //@Value("${web.upload-path}")
    //String FilePath = "d:/upload/my-java.png";
    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    Configuration cfg = new Configuration(Zone.zone2());
    //Zone z = Zone.zone1();
    //Configuration c = new Configuration(z);
    //创建上传对象
    UploadManager uploadManager = new UploadManager(cfg);

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken() {
        return auth.uploadToken(bucketname);
    }

    private static Set<String> imageSet = new HashSet<String>();

    static {
        imageSet.add(".png");
        imageSet.add(".jpg");
        imageSet.add(".jpeg");
        imageSet.add(".gif");
        imageSet.add(".bmp");
    }

//    @PostMapping("/upload")
//    public Result upload(@RequestParam("upfile")MultipartFile in) throws IOException {
//        try {
//            //调用put方法上传
//            String newFileName = "upload/"+System.currentTimeMillis() + getExtension(in.getOriginalFilename());
//            //String realPath = "/upload/";
//            //File dstFile = new File(realPath,newFileName);
//            //FileUtils.copyInputStreamToFile(in.getInputStream(), dstFile);
//            Response res = uploadManager.put(in.getInputStream(), newFileName, getUpToken(),null,null);
//            //打印返回的信息
//            System.out.println(res.bodyString());
//
//            if (res.isOK()) {
//                DefaultPutRet putRet = res.jsonToObject(DefaultPutRet.class);
//                System.out.println(putRet.key);
//                Map<Object,Object> map=new HashMap<Object, Object>();
//                map.put("key",putRet.key);
//                return Result.ok(null,map);
//                //return putRet.key;
//            } else {
//                return Result.fail(ResultCode.FAIL, res.error);
//            }
//        } catch (QiniuException e) {
//            Response r = e.response;
//            // 请求失败时打印的异常的信息
//            System.out.println(r.toString());
//            try {
//                //响应的文本信息
//                System.out.println(r.bodyString());
//            } catch (QiniuException e1) {
//                //ignore
//            }
//        }
//        return Result.fail(ResultCode.FAIL, "上传失败");
//         /* public static void main(String args[]) throws IOException{
//           new UploadUtil().upload();
//         }*/
//
//    }

    @PostMapping("/uploadImg")
    public Result upload(HttpServletRequest request) throws IOException {
        if(request instanceof MultipartHttpServletRequest){
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
            Map<String,MultipartFile> multipartFileMap = multipartHttpServletRequest.getFileMap();
            MultipartFile upfile = null;
            if(multipartFileMap.containsKey("upfile")){
                upfile = multipartFileMap.get("upfile");
            }
            if(upfile == null && multipartFileMap.containsKey("file")){
                upfile = multipartFileMap.get("file");
            }
            if(upfile == null){
                Iterator<Map.Entry<String,MultipartFile>> files = multipartFileMap.entrySet().iterator();
                if(files.hasNext()){
                    upfile = files.next().getValue();
                }
            }
            if(upfile == null){
                return Result.fail(ResultCode.FAIL,"未上传文件");
            }
            try {
                //调用put方法上传
                String newFileName = "upload/"+System.currentTimeMillis() + getExtension(upfile.getOriginalFilename());
                //String realPath = "/upload/";
                //File dstFile = new File(realPath,newFileName);
                //FileUtils.copyInputStreamToFile(in.getInputStream(), dstFile);
                Response res = uploadManager.put(upfile.getInputStream(), newFileName, getUpToken(),null,null);
                //打印返回的信息
                System.out.println(res.bodyString());

                if (res.isOK()) {
                    DefaultPutRet putRet = res.jsonToObject(DefaultPutRet.class);
                    System.out.println(putRet.key);
                    Map<Object,Object> map=new HashMap<Object, Object>();
                    map.put("key",putRet.key);
                    return Result.ok(null,map);
                    //return putRet.key;
                } else {
                    return Result.fail(ResultCode.FAIL, res.error);
                }
            } catch (QiniuException e) {
                Response r = e.response;
                // 请求失败时打印的异常的信息
                System.out.println(r.toString());
                try {
                    //响应的文本信息
                    System.out.println(r.bodyString());
                } catch (QiniuException e1) {
                    //ignore
                }
            }
            return Result.fail(ResultCode.FAIL, "上传失败");
        }
        return Result.fail(ResultCode.FAIL,"未上传文件");
    }

    /*@PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        try {
            //调用put方法上传
            String newFileName = "upload/business/" + System.currentTimeMillis() + getExtension(file.getOriginalFilename());
            //String realPath = "/upload/";
            //File dstFile = new File(realPath,newFileName);
            //FileUtils.copyInputStreamToFile(in.getInputStream(), dstFile);
            Response res = uploadManager.put(file.getInputStream(), newFileName, getUpToken(), null, null);
            //打印返回的信息
            System.out.println(res.bodyString());

            if (res.isOK()) {
                DefaultPutRet putRet = res.jsonToObject(DefaultPutRet.class);
                System.out.println(putRet.key);
                return Result.ok("", putRet.key);
                //return putRet.key;
            } else {
                return Result.fail(ResultCode.FAIL);
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
            return Result.fail(ResultCode.FAIL);
        }
    }*/

    /**
     * 获取文件后缀名
     *
     * @param fileName
     * @return
     */
    private String getExtension(String fileName) {
        int pos = fileName.lastIndexOf(".");
        if (pos > 0) {
            fileName = fileName.substring(pos);
        }
        return fileName;
    }


   /* @RequestMapping("/edit")
    public String edit(@RequestParam("file") MultipartFile pic, HttpServletRequest request) throws Exception {
        //获取流数据，方便存储
        FileItem fi = pic.getFileItem();


        //pic.getOriginalFilename()获取文件名
        //上传文件到服务器路径中
        File fi=new File(request.getRealPath("/")+"/file/"+pic.getOriginalFilename());
        fi.write(file);
        System.out.println("file=====================");
        return "gouwuche/edit";
    }*/


    @RequestMapping(value="/upload",method=RequestMethod.POST)
    @ResponseBody
    public String upload(MultipartFile file,HttpServletRequest request) throws IOException{
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        File dir = new File(path,fileName);
        if(!dir.exists()){
            dir.mkdirs();
        }

        try {
            file.transferTo(dir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }



}